<template>
    <view class="container">
        <view class="left-bottom-sign"></view>
        <view class="right-top-sign"></view>
        <!-- 设置白色背景防止软键盘把下部绝对定位元素顶上来盖住输入框等 -->
        <view class="wrapper">
            <view class="left-top-sign">LOGIN</view>
            <view class="welcome">
                欢迎回来！
            </view>
            <view class="input-content">
                <view class="input-item">
                    <text class="tit">手机号</text>
                    <input type="text" v-model="username" placeholder="请输入手机账号" maxlength="11" />
                </view>
                <view class="input-item">
                    <text class="tit">密码</text>
                    <input type="text" v-model="password" placeholder="输入账号密码" placeholder-class="input-empty"
                        maxlength="20" password @confirm="login" />
                </view>
            </view>
            <button class="confirm-btn" @click="toLogin" :disabled="logining">登录</button>
            <!-- <button class="" @click="username = 'boss';login()" :disabled="logining">测试登录（老板）</button>
            <button class="" @click="username = 'chief';login()" :disabled="logining">测试登录（大组长）</button>
            <button class="" @click="username = 'leader';login()" :disabled="logining">测试登录（小组长）</button>
            <button class="" @click="username = 'staff';login()" :disabled="logining">测试登录（员工）</button>
            <button class="" @click="username = 'merchant';login()" :disabled="logining">测试登录（商家）</button>
            <view class="forget-section">
                还没有账号?
                <text @tap="toRegist">马上注册</text>
            </view> -->
        </view>

        <view class="absolute b-30 w-full">
            <!-- 微信登录 -->
            <view @tap="wxLogin" class="f-c-c flex-col mb-26">
                <view class="color-grey text-80 mb-16">第三方登录</view>
                <image class="w-44 h-44" src="/static/wechat.svg"></image>
            </view>
        </view>
    </view>
</template>

<script>
    import {
        mapMutations
    } from 'vuex';
    import {
        tabBar
    } from '@/utils/tabBar.js';
    import {
        authApi
    } from '@/api';
    import {
        Token,
        User
    } from '@/utils'
    export default {
        data() {
            return {
                username: '',
                password: '',
                logining: false,
            }
        },
        onLoad() {
            this.username = uni.getStorageSync('username') || '';
            this.password = uni.getStorageSync('password') || '';
        },
        methods: {
            ...mapMutations(['login']),
            navBack() {
                uni.navigateBack();
            },
            toRegist() {
                uni.getUserProfile({
                    desc: '获取用户信息',
                    success: res => {
                        console.log(res);
                        uni.setStorageSync("wxInfo", JSON.stringify(res));
                        let nickName = res.userInfo.nickName;
                        let avatar = res.userInfo.avatarUrl;
                        this.userInfo = res.userInfo;
                    },
                    fail: res => {
                        console.log(res);
                    }
                });

                uni.navigateTo({
                    url: '/pages/public/register'
                });
            },
            login() {
                //假设这里是登录api请求
                // api.login(this.username, this.password).then(response => {
                // const role = response.data.role;
                // this.$store.dispatch('updateUserRole',role);
                this.navigateAfterLogin(this.username);
                // }).catch(error => {
                // 	console.error('登录失败', error);
                // });
            },
            navigateAfterLogin(username) {
                let identify = '';
                identify = username;
                uni.switchTab({
                    url: tabBar[username][0]["pagePath"]
                });
                uni.setStorageSync('identify', identify);
            },
            async toLogin() {
                this.logining = true;
                uni.showLoading({
                    title: '正在登录',
                    mask: true
                })
                authApi.login({
                    phone: this.username,
                    // userName: this.username,
                    password: this.password
                }).then(response => {
                    if (response.code == 200) {
                        this.loginSucc(response.data);
                    } else {
                        this.logining = false;
                        uni.hideLoading();
                        uni.showToast({
                            icon: 'error',
                            title: response.message,
                        })
                    }

                }).finally(() => {
                    this.logining = false;
                });
            },
            async wxLogin() {
                uni.showLoading({
                    title: '正在登录',
                    mask: true
                })
                let loginRes = await uni.login();
                loginRes = loginRes[1];
                console.log(loginRes);
                const {
                    code,
                    data,
                    message
                } = await authApi.wxLogin(loginRes.code);
                if (code == 200) {
                    this.loginSucc(data);
                } else {
                    this.logining = false;
                    uni.hideLoading();
                    uni.showToast({
                        icon: 'error',
                        title: message,
                    })
                }
            },
            async fechUserInfo(userId) {
                uni.showLoading({
                    title: '请稍候',
                    mask: true
                })
                const {
                    code,
                    data
                } = await authApi.getUserInfoById(userId);
                uni.hideLoading();
                if (code == 200) {
                    User.set(data);
                    return data;
                }
                return null;
            },

            async loginSucc(data) {
                console.log('loginSucc参数————————————')
                console.log(data)
                if (data.token) {
                    let token = data.tokenHead + data.token;
                    Token.set(token);
                }
                const userInfoData = await this.fechUserInfo(data.userId);
                User.set(userInfoData);
                if (userInfoData.openid == null) {
                    uni.hideLoading();
                    uni.showModal({
                        title: '首次登录',
                        content: `请确认您的信息\n姓名：${data.userName}\n手机号：${data.phone}`,
                        confirmText: '是我',
                        cancelText: '不是我',
                        success: (res) => {
                            if (res.confirm) {
                                this.firstLogin(data);
                            } else if (res.cancel) {
                                uni.showToast({
                                    icon: 'none',
                                    title: '请重新输入账号'
                                })
                                return;
                            }
                        }
                    });
                } else {
                    uni.setStorageSync('username', this.username);
                    uni.setStorageSync('password', this.password);
                    let navigateTo; // 用于存储导航路径
                    console.log(`当前roleId：${data.roleId}`)
                    switch (data.roleId) {
                        case '6':
                            navigateTo = 'boss';
                            break;
                        case '7':
                            navigateTo = 'chief';
                            break;
                        case '8':
                            navigateTo = 'leader';
                            navigateTo = 'staff';//小组长也用工人界面
                            break;
                        case '9':
                            navigateTo = 'staff';
                            break;
                        case '10':
                            navigateTo = 'merchant';
                            break;
                        default:
                            navigateTo = 'unknow';
                            break;
                    }

                    this.navigateAfterLogin(navigateTo);
                }

            },

            async firstLogin(loginData) {
                uni.showLoading();
                await uni.requestSubscribeMessage({
                    tmplIds: ['80r1vE7SGrwM2YmvbhlYT2NW9kd5R9vm9hXwGkZdaYY'],
                    success: async (res) => {
                        if (res['80r1vE7SGrwM2YmvbhlYT2NW9kd5R9vm9hXwGkZdaYY'] == 'accept') {
                            uni.showLoading({
                                title: "请稍候"
                            })
                            try {
                                let loginRes = await uni.login();
                                loginRes = loginRes[1];
                                const {
                                    code,
                                    data
                                } = await authApi.wxBind(loginData.userId, loginRes.code);
                                if (code == 200) {
                                    this.refreshUserInfo(loginData.userId);
                                    uni.showToast({
                                        title: '绑定成功'
                                    })
                                }
                            } finally {
                                // uni.hideLoading();
                            }
                        } else {
                            uni.showToast({
                                icon: 'error',
                                title: '请同意接受通知'
                            })
                            return
                        }

                    },
                    fail(res) {
                        return
                    },
                    complete(res) {
                        console.log('微信通知权限回调值：')
                        console.log(res);
                    }
                });
            },
            async refreshUserInfo(userId) {
                const {
                    code,
                    data
                } = await authApi.getUserInfoById(userId);
                if (code == 200) {
                    this.loginSucc(data);
                }
            },

        }

    }
</script>

<style lang='scss'>
    page {
        background: #fff;
    }

    .container {
        padding-top: 115px;
        position: relative;
        width: 100vw;
        height: 100vh;
        overflow: hidden;
        background: #fff;
    }

    .wrapper {
        position: relative;
        z-index: 90;
        padding-bottom: 40upx;
    }

    .back-btn {
        position: absolute;
        left: 40upx;
        z-index: 9999;
        padding-top: var(--status-bar-height);
        top: 40upx;
        font-size: 40upx;
        color: $font-color-dark;
    }

    .left-top-sign {
        font-size: 120upx;
        color: $page-color-base;
        position: relative;
        left: -16upx;
    }

    .right-top-sign {
        position: absolute;
        top: 80upx;
        right: -30upx;
        z-index: 95;

        &:before,
        &:after {
            display: block;
            content: "";
            width: 400upx;
            height: 80upx;
            background: #b4f3e2;
        }

        &:before {
            transform: rotate(50deg);
            border-radius: 0 50px 0 0;
        }

        &:after {
            position: absolute;
            right: -198upx;
            top: 0;
            transform: rotate(-50deg);
            border-radius: 50px 0 0 0;
            /* background: pink; */
        }
    }

    .left-bottom-sign {
        position: absolute;
        left: -270upx;
        bottom: -320upx;
        border: 100upx solid #d0d1fd;
        border-radius: 50%;
        padding: 180upx;
    }

    .welcome {
        position: relative;
        left: 50upx;
        top: -90upx;
        font-size: 46upx;
        color: #555;
        text-shadow: 1px 0px 1px rgba(0, 0, 0, .3);
    }

    .input-content {
        padding: 0 60upx;
    }

    .input-item {
        display: flex;
        flex-direction: column;
        align-items: flex-start;
        justify-content: center;
        padding: 0 30upx;
        background: $page-color-light;
        height: 120upx;
        border-radius: 4px;
        margin-bottom: 50upx;

        &:last-child {
            margin-bottom: 0;
        }

        .tit {
            height: 50upx;
            line-height: 56upx;
            font-size: $font-sm+2upx;
            color: $font-color-base;
        }

        input {
            height: 60upx;
            font-size: $font-base + 2upx;
            color: $font-color-dark;
            width: 100%;
        }
    }

    .confirm-btn {
        width: 630upx;
        height: 76upx;
        line-height: 76upx;
        border-radius: 50px;
        margin-top: 70upx;
        background: $uni-color-primary;
        color: #fff;
        font-size: $font-lg;

        &:after {
            border-radius: 100px;
        }
    }

    .confirm-btn2 {
        width: 630upx;
        height: 76upx;
        line-height: 76upx;
        border-radius: 50px;
        margin-top: 40upx;
        background: $uni-color-primary;
        color: #fff;
        font-size: $font-lg;

        &:after {
            border-radius: 100px;
        }
    }

    .forget-section {
        font-size: $font-sm+2upx;
        text-align: center;
        margin-top: 40upx;

        text {
            color: $font-color-spec;
            margin-left: 10upx;
        }
    }
</style>